<?php
/**
 * Created by PhpStorm.
 * User: FDG296
 * Date: 2017/8/2
 * Time: 16:42
 */
namespace backend\models;

use Yii;
use yii\db\ActiveRecord;

class GoodsSaleEdit extends ActiveRecord{
    const STATUS_ENABLE = 1;
    const STATUS_DISABLE = 0;
    
    const USE_FLG_YES	= 1;
    const USE_FLG_NO	= 0;

    public static function tableName(){
        return '{{%goods_sale_edit}}';
    }

    public function rules(){
        return [
            ['use_flg','default','value'=>self::STATUS_DISABLE],
            ['creator','getCreator'],
            ['create_time','date']
        ];
    }

    /**
     * @获取创建人
     */
    public function getCreator(){
        $userInfo = \common\helps\tools::getloginUserInfo();
        if($userInfo){
            $userName = $userInfo->userName;
        }else{
            $userName = '';
        }
        return $userName;
    }
    
    /**
     * @param $main_goods_id
     * @param $spec
     * @param int $spec_color
     * @return array|null|ActiveRecord
     */
    public static  function getGoodsSaleInfo($main_goods_id,$spec=0,$spec_color = 0){
        $params = [
            'main_goods_id'	=>$main_goods_id,
            'spec'			=>$spec,
            'spec_color'	=>$spec_color,
            'use_flg'		=>self::USE_FLG_YES
        ];
        $where	= array_filter($params);
        
        return self::find()
        ->where($where)
        ->asArray()
        ->groupBy(['spec'])
        ->all();
    }

    //同步商品
    public function publishGoodsSkuList($main_goods_id_list){

        $is_complete = true;
        foreach($main_goods_id_list as $goods){
            $need_goods = $goods;
            if($goods['is_publish'] == 1){ //已同步
                unset($need_goods['sales_cnt']);
                unset($need_goods['is_publish']);
                unset($need_goods['id']);
                unset($need_goods['creator']);
                unset($need_goods['create_time']);
                $need_goods['editor'] = $this->getCreator();
                $need_goods['edit_time'] = date('Y-m-d H:i:s',time());
                $res = GoodsSale::updateAll($need_goods,'goods_id=:goods_id',array(':goods_id'=>$goods['goods_id']));
            }else{ //未同步
                unset($need_goods['is_publish']);
                unset($need_goods['id']);
                $need_goods['creator'] = $this->getCreator();
                $need_goods['create_time'] = date('Y-m-d H:i:s',time());
                $res = Yii::$app->db->createCommand()->insert('j_goods_sale',$need_goods)->execute();
            }
            $del_source = GoodsSource::deleteAll(['goods_id'=>$goods['goods_id']]);
            $source_edit = GoodsSourceEdit::find()->where('use_flg=1 and goods_id='.$goods['goods_id'])->asArray()->all();
            if (is_array($source_edit) && count($source_edit) > 0)foreach ($source_edit as $source_val){
                unset($source_val['id']);
                unset($source_val['creator']);
                unset($source_val['create_time']);
                $source_val['editor'] = $this->getCreator();
                $source_val['edit_time'] = date('Y-m-d H:i:s',time());
                $res = Yii::$app->db->createCommand()->insert('j_goods_source',$source_val)->execute();
            }
           
            if(!$res){
                $is_complete = false;
                break;
            }
        }
        return $is_complete;
    }
    
    /**
     * @param 根据主商品ID 获取相同规格 相同颜色的的商品
     * @param 没有 $spec 和$specColor 返回售卖商品关联的信息
     */
    public static function getIdenticalMainGoods($mainGoodsId,$spec='',$specColor=''){
        
        $params = [
            self::tableName().'.main_goods_id'	=>$mainGoodsId,
            //GoodsSpecRelation::tableName().'.main_goods_id'	=>$mainGoodsId,
            self::tableName().'.spec'			=>$spec,
            self::tableName().'.spec_color'	=>$specColor,
            self::tableName().'.use_flg'	=>self::USE_FLG_YES,
        ];
        $where	= array_filter($params);
        
        //关联信息
        $relation	= '';
        if($spec){
            $relation	= 'specColorRelation';
        }
        
        if($specColor){
            $relation	= 'specRelation';
        }
        
        return self::find()
        ->where($where)
        ->joinWith($relation)
        //->createCommand()->getRawSql();
        ->asArray()
        ->all();
    }
    
    //根据goods_id获取商品的规格，颜色，价格
    public function getGoodsListByMainId($main_goods_id){
        if(!empty($main_goods_id)){
            $where = ['main_goods_id'=>$main_goods_id,'use_flg'=>1];
            $result = $this::find()->where($where)->select('sku,series,model,goods_id,spec,spec_val,spec_color,spec_color_val,sale_price,market_price')->asArray()->all();
        }
        if(empty($result)){
            $result = array();
        }
        return $result;
    }
    
    //获取sku列表
    public function getSkuList($main_goods_id,$spec,$spec_color){
        $sku_list = array();
        $where['main_goods_id'] = $main_goods_id;
        if(!empty($spec)){
            $where['spec'] = $spec;
        }
        if(!empty($spec_color)){
            $where['spec_color'] = $spec_color;
        }
        //$where = ['main_goods_id'=>$main_goods_id,'spec'=>$spec,'spec_color'=>$spec_color];
        $main_goods_list = $this::find()->where($where)->select('sku,id')->asArray()->all();
        if(!empty($main_goods_list)){
            $sku_list = array_column($main_goods_list,'sku');
        }
        return $sku_list;
    }
    
    //获取goods_id列表
    public function getGoodsIdList($main_goods_id,$spec,$spec_color){
        $sku_list = array();
        $where['main_goods_id'] = $main_goods_id;
        if(!empty($spec)){
            $where['spec'] = $spec;
        }
        if(!empty($spec_color)){
            $where['spec_color'] = $spec_color;
        }
        //$where = ['main_goods_id'=>$main_goods_id,'spec'=>$spec,'spec_color'=>$spec_color];
        $main_goods_list = $this::find()->where($where)->select('goods_id,id')->asArray()->all();
        if(!empty($main_goods_list)){
            $sku_list = array_column($main_goods_list,'goods_id');
        }
        return $sku_list;
    }
    
    //获取goods_id
    public function getGoodsId($main_goods_id,$spec,$spec_color = 0){
        $goods_id = '';
        $where = ['main_goods_id'=>$main_goods_id,'spec'=>$spec,'spec_color'=>$spec_color];
        $main_goods_list = $this::find()->where($where)->select('goods_id,id')->asArray()->one();
        if(!empty($main_goods_list)){
            $goods_id = $main_goods_list['goods_id'];
        }
        return $goods_id;
    }
    
    /**
     * @param 关联表信息 查询规格关联表（关联规格）
     * @return \yii\db\ActiveQuery
     */
    public function getSpecRelation(){
        return $this->hasOne(GoodsSpecRelation::className(),['spec_id'=>'spec']);
    }
    
    /**
     * @param 关联表信息 查询规格关联表（关联颜色）
     * @return \yii\db\ActiveQuery
     */
    public function getSpecColorRelation(){
        return $this->hasOne(GoodsSpecRelation::className(),['spec_id'=>'spec_color','main_goods_id'=>'main_goods_id']);
    }
    
    /**
     * @param 关联表信息 查询规格关联表（关联主商品） 查询所有商品的规格信息
     * @param 售卖商品表缺少对应的规格主键ID
     * @return \yii\db\ActiveQuery
     */
    public function getMainSpecRelation(){
        return $this->hasOne(GoodsSpecRelation::className(),['main_goods_id'=>'main_goods_id']);
    }
}